package com.joney.backstage.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.joney.backstage.constant.Constants;
import com.joney.backstage.constant.Permissions;
import com.joney.backstage.constant.WebPageEL;
import com.joney.backstage.dto.RoleEditReq;
import com.joney.backstage.dto.UserRoleRsp;
import com.joney.backstage.entity.Role;
import com.joney.backstage.entity.RoleResource;
import com.joney.backstage.entity.UserRole;
import com.joney.backstage.mapper.RoleMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.joney.common.pojo.Result;
import com.joney.common.utils.JudgeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author joney123
 * @since 2018-02-07
 */
@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleResourceService roleResourceService;
    /**
     * @desc 获取用户拥有的所有角色
     * @author wangxianchen
     * @create 2018-02-07
     * @param userId
     * @return
     */
    public Set<String> getRolesByUserId(Integer userId){
        List<Role> roleList = baseMapper.selectRolesByUserId(userId);
        Set<String> roleSet = new HashSet<>();
        if(JudgeUtil.isNotEmpty(roleList)){
            for(Role role : roleList){
                roleSet.add(String.valueOf(role.getId()));
            }
        }
        return roleSet;
    }

    public List<Role> selectRolesByResId(Integer resId){
        return baseMapper.selectRolesByResId(resId);
    }

    public Map<String,Boolean> getMgrPermission(int curLoginUserId){
        Map<String,Boolean> authMap = new HashMap<>();
        authMap.put(WebPageEL.CAN_ADD,false);
        authMap.put(WebPageEL.CAN_EDIT,false);
        authMap.put(WebPageEL.CAN_DEL,false);
        authMap.put(WebPageEL.CAN_USER_OPT,false);
        authMap.put(WebPageEL.CAN_RES_OPT,false);
        authMap.put(WebPageEL.CAN_ROLE_BIND_RES_OPT,false);
        List<String> permissionList = userRoleService.getPermissions(curLoginUserId);
        if(permissionList != null && permissionList.size() > 0){
            for(String permission : permissionList){
                if(permission != null){
                    if(permission.equals(Permissions.SYS_ROLE_ADD)){
                        authMap.put(WebPageEL.CAN_ADD,true);
                    }else if(permission.equals(Permissions.SYS_ROLE_EDIT)){
                        authMap.put(WebPageEL.CAN_EDIT,true);
                    }else if(permission.equals(Permissions.SYS_ROLE_DEL)){
                        authMap.put(WebPageEL.CAN_DEL,true);
                    }else if(permission.equals(Permissions.SYS_ROLE_USER_VIEW)){
                        authMap.put(WebPageEL.CAN_USER_OPT,true);
                    }else if(permission.equals(Permissions.SYS_ROLE_RES_VIEW)){
                        authMap.put(WebPageEL.CAN_RES_OPT,true);
                    }else if(permission.equals(Permissions.SYS_ROLE_RES_BIND)){
                        authMap.put(WebPageEL.CAN_ROLE_BIND_RES_OPT,true);
                    }

                }
            }
        }
        return authMap;
    }

    public Map<String,Boolean> getBindPermission(int curLoginUserId){
        Map<String,Boolean> authMap = new HashMap<>();
        authMap.put(WebPageEL.CAN_ROLE_BIND_USER_OPT,false);
        List<String> permissionList = userRoleService.getPermissions(curLoginUserId);
        if(permissionList != null && permissionList.size() > 0){
            for(String permission : permissionList){
                if(permission != null){
                    if(permission.equals(Permissions.SYS_ROLE_USER_BIND)){
                        authMap.put(WebPageEL.CAN_ROLE_BIND_USER_OPT,true);
                    }
                }
            }
        }
        return authMap;
    }

    public Result updateRole(RoleEditReq params, int operatorId){
        Role role = baseMapper.selectById(params.getId());
        if(role == null){
            return Result.fail("不存在的角色");
        }
        //超级管理员角色只能由超级管理员自己编辑
        if(role.getId() == Constants.SUPER_ADMINISTRATOR_ROLE_ID && operatorId != Constants.SUPER_ADMINISTRATOR_ROLE_ID){
            return Result.fail("无权编辑超级管理员角色");
        }
        role = new Role();
        BeanUtils.copyProperties(params,role);
        role.setUpdateUser(operatorId);
        baseMapper.updateById(role);
        return Result.success();
    }

    public List<UserRoleRsp> queryBind(Page page, Map<String,Object> params){
        return userRoleService.queryBind(page,params);
    }

    public List<UserRoleRsp> queryNotBindUser(Page page, Map<String,Object> params){
        return userRoleService.queryNotBindUser(page,params);
    }

    public Result bindUser(int roleId, int bindState, String userIds, int operatorId){
        return userRoleService.bindUser(roleId,bindState,userIds,operatorId);
    }

    public Result bindRes(int roleId, String addResIds, String delResIds, int operatorId){
        boolean flag = true;
        if(addResIds != null && addResIds.trim().length()>0){
            String[] ids = addResIds.split("-");
            if(ids != null && ids.length > 0){
                List<RoleResource> roleResList = new ArrayList<>(ids.length);
                for(String resId:ids){
                    RoleResource temp = new RoleResource();
                    temp.setRoleId(roleId);
                    temp.setResId(Integer.valueOf(resId));
                    temp.setCreateUser(operatorId);
                    roleResList.add(temp);
                }
                flag = roleResourceService.insertBatch(roleResList,ids.length);
            }

        }
        if(!flag){
            return Result.fail("数据更新失败");
        }
        if(delResIds != null  && delResIds.trim().length()>0){
            String[] ids = delResIds.split("-");
            if(ids != null && ids.length > 0){
                EntityWrapper<RoleResource> wrapper = new EntityWrapper<>();
                wrapper.eq("role_id",roleId);
                wrapper.in("res_id",ids);
                roleResourceService.delete(wrapper);
            }
        }
        return Result.success();
    }

    public Result deleteRole(int roleId){
        Role role = this.selectById(roleId);
        if(role == null){
            return Result.fail("角色不存在，请刷新重试");
        }
        if(role.getId() == Constants.SUPER_ADMINISTRATOR_ROLE_ID){
            return Result.fail("超级管理员角色不可以删除");
        }
        EntityWrapper<UserRole> wrapper = new EntityWrapper();
        wrapper.eq("role_id",roleId);
        int count = userRoleService.selectCount(wrapper);
        if(count > 0){
            return Result.fail("请先解除角色绑定的用户");
        }
        if(!this.deleteById(roleId)){
            return Result.fail("删除失败，请刷新重试！");
        }
        return Result.success();
    }
}
